<template>
  <div v-loading="examineLoading || listLoading" :element-loading-text="elementLoadingText">
    <!--v-table-fixed-scrollbar="{ bottom: 71 }"-->
    <u-table
      v-if="list && list.items.length"
      ref="orderTable"
      :data="list.items"
      :row-class-name="(data) => tableRowClassName(data)"
      :height="tableHeight"
      :row-height="showMobilePage ? 40 : 49"
      :border="true"
      :key="tableKey"
      beautify-table
      header-drag-style
      use-virtual
      class="fb-table"
      element-loading-text="加载中..."
      empty-text="暂无数据"
      header-cell-class-name="order-data-header-cell "
      fit
      hightlight-current-row
      @sort-change="sortMethod"
      @select="selectTable"
      @select-all="selectTable">
      <u-table-column v-if="!hideSelection" align="center" fixed="left" type="selection" width="50"/>
      <u-table-column
        v-if="isDustbin"
        align="left"
        label="删除时间"
        prop="deleteTime"
        sortable="custom"
        width="175">
        <template slot-scope="scope">
          <div v-if="scope.row.deleteTime">{{ scope.row.deleteTime | format('YYYY/MM/DD HH:mm:ss') }}</div>
          <div v-else>--</div>
        </template>
      </u-table-column>
      <!-- <template v-if="orderListSettingPure && !$parent.$el.offsetParent.className.includes('fixed')">
        <u-table-column
          v-for="settingItem in orderListSettingPure"
          :key="settingItem.name"
          :label="settingItem.name"
          align="left">
          <template slot-scope="scope">
            <columnRender :field-name="settingItem.fieldName" :scope="scope" :log="$children[0].$el.children"/>
          </template>
        </u-table-column>
      </template> -->
      <!-- :key="index" -->
      <template v-for="(settingItem, index) in orderListSetting">
        <u-table-column
          v-if="settingItem.isShow && (orderProps[settingItem.fieldName] || orderProps[`${settingItem.secondField || ''}.${settingItem.fieldName}`])"
          :key="index"
          v-bind="!settingItem.secondField ? orderProps[settingItem.fieldName] : orderProps[`${settingItem.secondField}.${settingItem.fieldName}`]"
        >
          <template slot-scope="scope">
            <!-- 订单类型 -->
            <template v-if="settingItem.fieldName === 'orderType'">
              <div :style="{background: scope.row.bg || 'rgb(253, 239, 233)', color: scope.row.color || 'rgb(253, 133, 70)'}" class="order-type" @click="btnCheck(scope)">
                {{ scope.row.orderType | orderTypeStatusFilter }}
              </div>
            </template>
            <!-- 下单日期 -->
            <template v-else-if="settingItem.fieldName === 'orderTime'">
              <div v-if="scope.row.orderTime">{{ scope.row.orderTime | standardFormatNoHour('YYYY/MM/DD') }}</div>
              <div v-else>--</div>
            </template>
            <!-- 联系人 -->
            <template v-else-if="settingItem.fieldName === 'contactPerson'">
              <ToolTip :content="scope.row.contactPerson" />
            </template>
            <!-- 关联询单 -->
            <template v-else-if="settingItem.fieldName === 'queryOrderSn'">
              <ToolTip :content="scope.row.queryOrderSn" is-can-click @handelClick="goFlyNoticeDetail(scope.row)" />
            </template>
            <!-- 销售 -->
            <template v-else-if="settingItem.fieldName === 'market'">
              <CheckUserInfo v-if="scope.row.market" :label="scope.row.market" :user-id="scope.row.clientInfo.marketId" />
              <div v-else>--</div>
            </template>
            <!-- 客户名称 -->
            <template v-else-if="settingItem.fieldName === 'clientName'">
              <ToolTip :content="scope.row.clientName" />
            </template>
            <!-- 实际客户名称 -->
            <template v-else-if="settingItem.fieldName === 'actualClientName'">
              <ToolTip :content="scope.row.clientInfo && scope.row.clientInfo.actualClientName" />
            </template>
            <!-- 客户订单编号 -->
            <template v-else-if="settingItem.fieldName === 'customerOrderNum'">
              <ToolTip :content="scope.row.clientInfo && scope.row.clientInfo.customerOrderNum" />
            </template>
            <!-- 所属集团 -->
            <template v-else-if="settingItem.fieldName === 'group'">
              <ToolTip :content="scope.row.group" />
            </template>
            <!-- 收入类型 -->
            <template v-else-if="settingItem.fieldName === 'incomeType'">
              <div v-if="scope.row.incomeTypeStr">{{ scope.row.incomeTypeStr || '--' }}</div>
              <div v-else-if="scope.row.incomeTypeStr === 0">{{ scope.row.incomeTypeStr }}</div>
              <div v-else>--</div>
            </template>
            <!-- 所属部门 -->
            <template v-else-if="settingItem.fieldName === 'attributionMatrix'">
              <el-tooltip v-if="scope.row.attributionMatrixName" :open-delay="800" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">
                  {{ (scope.row.attributionMatrixFullName || scope.row.attributionMatrixName) | getDeptFullName }}
                </div>
                <div class="client-name ellipsisOne">{{ scope.row.attributionMatrixName }}</div>
              </el-tooltip>
              <div v-else class="client-name ellipsisOne" style="width: 110px;">--</div>
            </template>
            <!-- 账号名称 -->
            <template v-else-if="settingItem.fieldName === 'resourceName'">
              <div style="display:flex;align-items:center;">
                <frameContent
                  v-if="scope.row.dataAccount"
                  :platform="scope.row.orderPlatform || scope.row.accountNamePlatform"
                  :data-account="scope.row.dataAccount"
                  :url="scope.row.dataLink"
                  :account-id="scope.row.orderInfo.resourceId"
                  :account-name="scope.row.orderInfo.resourceName" />
                <resource-info
                  v-if="scope.row.orderInfo.resourceType !== 1 && scope.row.orderInfo.resourceType !== 2"
                  :resource-name="scope.row.resourceName"
                  :account-name-organization="scope.row.accountNameOrganization"
                  :account-name-platform="scope.row.accountNamePlatform"
                  :resource-id="scope.row.orderInfo.resourceCode"
                  account-belong-name="none"
                  style="max-width:calc(100% - 20px);"
                />
                <span v-else-if="scope.row.orderInfo.resourceType === 1">多账号</span>
                <span v-else-if="scope.row.orderInfo.resourceType === 2">无号单</span>
              </div>
            </template>
            <!-- 下单平台 -->
            <template v-else-if="settingItem.fieldName === 'orderPlatform'">
              <div class="flex-center">
                <platformIcon :data="scope.row.orderPlatform" :key="scope.row.id" />
                <el-tooltip v-if="scope.row.orderPlatform" :open-delay="800" class="item" placement="top" effect="dark">
                  <div slot="content" style="max-width: 200px;">{{ scope.row.orderPlatform }}</div>
                  <div class="client-name ellipsisOne">{{ scope.row.orderPlatform }}</div>
                </el-tooltip>
                <div v-else class="ellipsisOne">--</div>
              </div>
            </template>
            <!-- 合作运营方 -->
            <template v-else-if="settingItem.fieldName === 'cooperation'">
              <div class="flex-center">
                <el-tooltip v-if="scope.row.orderInfo.cooperation" :open-delay="800" class="item" placement="top" effect="dark">
                  <div slot="content" style="max-width: 200px;">{{ scope.row.orderInfo.cooperation }}</div>
                  <div class="client-name ellipsisOne">{{ scope.row.orderInfo.cooperation }}</div>
                </el-tooltip>
                <div v-else class="ellipsisOne">--</div>
              </div>
            </template>
            <template v-else-if="settingItem.fieldName === 'supplierType'">
              <div class="flex-center">
                <ToolTip v-if="scope.row.orderInfo.supplierType !== null" :content="scope.row.orderInfo.supplierType | getSupplierType" />
                <div v-else class="ellipsisOne">--</div>
              </div>
            </template>
            <!-- 含税金额 -->
            <template v-else-if="settingItem.fieldName === 'taxAmount'">
              <PriceColumn :real-val="scope.row.taxAmount" :price="scope.row.taxAmount / 100" />
            </template>
            <!-- 核销金额 -->
            <template v-else-if="settingItem.fieldName === 'completeWriteOffAmount'">
              <PriceColumn :real-val="scope.row.financeRecord.completeWriteOffAmount" :price="scope.row.financeRecord.completeWriteOffAmount / 100" />
            </template>
            <!-- 待核销金额 -->
            <template v-else-if="settingItem.fieldName === 'unWriteOffAmount'">
              <PriceColumn :real-val="scope.row.financeRecord.unWriteOffAmount" :price="scope.row.financeRecord.unWriteOffAmount / 100" />
            </template>

            <!-- 推广主题 -->
            <template v-else-if="settingItem.fieldName === 'theme'">
              <el-tooltip v-if="scope.row.theme && scope.row.theme.length > 5" :open-delay="800" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.theme }}</div>
                <div class="theme ellipsisOne">{{ scope.row.theme }}</div>
              </el-tooltip>
              <div v-else class="theme ellipsisOne">{{ scope.row.theme || '--' }}</div>
            </template>
            <!-- 核销状态 -->
            <template v-else-if="settingItem.fieldName === 'writeOffStatus'">
              <StatusText :color="scope.row.financeRecord.writeOffStatus?'#406EFF':'#999'" :text="scope.row.financeRecord.writeOffStatus | setAccountState" />
            </template>
            <!-- 是否开启采集 -->
            <template v-else-if="settingItem.fieldName === 'autoPick'">
              <div v-if="scope.row.publishInfo && typeof scope.row.publishInfo.autoPick === 'boolean'">{{ scope.row.publishInfo.autoPick ? '是' : '否' }}</div>
              <div v-else>--</div>
            </template>
            <!-- 审批状态 -->
            <template v-else-if="settingItem.fieldName === 'reviewState'">
              <StatusText :color="['#31CC9C','#406EFF','#FD8546'][scope.row.reviewState]" :text="scope.row.reviewState | setReviewState" />
            </template>
            <!-- 封账状态 -->
            <template v-else-if="settingItem.fieldName === 'sealBillType'">
              <StatusText :color="scope.row.sealBillType?'#999':'#406EFF'" :text="scope.row.sealBillType | setSealBillType" />
            </template>
            <!-- 订单状态 -->
            <template v-else-if="settingItem.fieldName === 'orderStatus'">
              <div>
                <div v-if="scope.row.orderStatus || scope.row.orderStatus === 0" >
                  <div style="display:flex;align-items:center;">
                    <span :style="{backgroundColor: getColor(scope.row.orderStatus)}" class="dot"/>
                    {{ scope.row.orderStatus | orderStatusFilter }}
                  </div>
                  <!-- 订单状态为封账中(5)时，展示审批状态 -->
                  <div v-if="false && scope.row.orderStatus === 5" style="display:flex;justify-content: center;">
                    <el-tag v-if="scope.row.reviewState === 0" size="small" type="success">{{ scope.row.reviewState | setReviewState }}</el-tag>
                    <el-tag v-if="scope.row.reviewState === 1" size="small">{{ scope.row.reviewState | setReviewState }}</el-tag>
                    <el-tag v-if="scope.row.reviewState === 2" size="small" type="danger">{{ scope.row.reviewState | setReviewState }}</el-tag>
                  </div>
                </div>
                <span v-else>--</span>
              </div>
            </template>
            <!-- 标签 -->
            <template v-else-if="settingItem.fieldName === 'tag'">
              <el-tooltip v-if="scope.row.orderInfo.tag && scope.row.orderInfo.tag.length" :open-delay="800" placement="top" effect="dark">
                <div slot="content" style="max-width:300px">{{ handleStr(scope.row.orderInfo.tag) }}</div>
                <div class="tag-wrap">
                  <span
                    v-for="(t,index) in handleTags(scope.row.orderInfo.tag)"
                    :key="index"
                    :style="t.color ? `color:${t.color};background:${changeColorAlphaVal(t.color, 0.14)}` : ''"
                    class="tag">
                    {{ t.name }}
                  </span>
                  <div v-if="scope.row.orderInfo.tag.length > 3">...</div>
                </div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
            <template v-else-if="settingItem.fieldName === 'supplierStatus'">
              <div v-if="scope.row.supplierStatus || scope.row.supplierStatus === 0"><supplierStatus :order-id="scope.row.id" :btn-text="`已结算${scope.row.supplierStatus || 0}个成本`" /></div>
              <div v-else>--</div>
            </template>
            <!-- 成本项列表 -->
            <template v-else-if="settingItem.fieldName === 'costNum'">
              <dialogCostlist :cost-list="scope.row.costBreakdown.costList || []" :order-id="scope.row.id" :btn-text="`共${scope.row.costListNun?scope.row.costListNun:0}项成本`" />
            </template>

            <!-- 关联发票,关联合同,微任务成本状态 ,成本-->
            <template
              v-else-if="settingItem.fieldName === 'linkInvoice' ||
                settingItem.fieldName === 'linkContract' ||
                settingItem.fieldName === 'microTaskCost' ||
              settingItem.fieldName === 'totalCost'">
              <div v-if="scope.row[settingItem.fieldName] === false || scope.row[settingItem.fieldName] === true">
                <span v-if="scope.row[settingItem.fieldName]">已填写</span>
                <span v-else>--</span>
              </div>
              <div v-else>--</div>
            </template>
            <!--订单详情的字段 -->
            <detailField
              v-else-if="settingItem.parentField === 'publishInfo' || settingItem.parentField === 'orderInfo' || settingItem.parentField === 'costBreakdown'|| settingItem.parentField === 'clientInfo'"
              :setting-item="settingItem"
              :is-blank="isBlank"
              :data-item="scope.row" />
            <!-- 客户结算状态 -->
            <template v-else-if="settingItem.fieldName === 'settleStatus'">
              <div>{{ scope.row.settlementStatus | clientSettlementStatus }}</div>
            </template>
          </template>
        </u-table-column>
      </template>
      <u-table-column
        v-if="showActionsColumn"
        align="left"
        label="操作"
        width="110"
        fixed="right">
        <template slot-scope="scope">
          <div class="flex-center">
            <div v-if="!isDustbin" class="button-text" @click="btnCheck(scope)">查看</div>
            <div v-if="isDustbin && hasRouteAuth('crm:orderList:dustbinDelete')" class="button-text" @click="()=> {$emit('toDeleteDialog', scope.row.id)}">删除</div>
            <!-- 最终单只能变更 orderType === 9-->
            <!-- orderType 0:原订单 1:拆分单 2:对冲单 3:新订单 4:补录单 5:调整单 6:多号单 7:补差单 8:变更单 9:最终单 -->
            <!-- orderStatus 0:草稿中 1:待发布 2:待核算 3:待审批 4:待封账 5:封账中 6:已封账 7:已完成 -->
            <MoreOpeator
              v-if="!isDustbin && scope.row.orderStatus !== 5"
              :list="[
                { // 不是最终单 && 待审批 && 有审批权限
                  label: '审批',
                  handelClick: () => { examine(scope.row) },
                  auth: scope.row.orderType !== 9 && scope.row.orderStatus === 3 && hasRouteAuth('crm:orderList:examine')
                },
                { // 不是最终单 && 待发布 && 有发布权限
                  label: '发布',
                  handelClick: () => { toPublishDialog(scope) },
                  auth: scope.row.orderType !== 9 && scope.row.orderStatus === 1 && isPublishAuth(scope.row)
                },
                {
                  label: '撤回',
                  handelClick: () => { revokeDialog(scope.row) },
                  auth: scope.row.orderType !== 9 &&
                    ((scope.row.orderStatus === 3 && (isExamineAuth() || isPublishAuth(scope.row))) ||
                    (scope.row.orderStatus === 4 && (isExamineAuth() || isAllAdmin(scope.row))))
                }, {
                  label: '编辑',
                  handelClick: () => { btnEdit(scope) },
                  auth: scope.row.orderType !== 9 && isEditAuth(scope.row) && scope.row.orderType !== 2 && scope.row.orderStatus !== 6 && scope.row.orderStatus !== 7
                }, {
                  label: '编辑',
                  handelClick: () => { btnEdit(scope) },
                  auth: scope.row.orderType !== 9 && (scope.row.orderStatus === 1 && hasRouteAuth('crm:orderList:toBeAnnoEdit'))
                }, {
                  label: '删除',
                  handelClick: () => { btnDel(scope) },
                  auth: scope.row.orderType !== 9 && scope.row.orderStatus < 4 && hasRouteAuth('crm:orderList:delete')
                },
                {
                  label: '变更',
                  handelClick: () => { changeOrder(scope) },
                  auth: scope.row.isShowChange && isEditAuth(scope.row) && scope.row.orderType !== 2 && (scope.row.orderStatus === 6 || scope.row.orderStatus === 7) && hasRouteAuth('crm:orderList:add'),
                }
              ]"
            >
              <div slot="button" class="button-text bl">更多<i class="el-icon-arrow-down"/></div>
            </MoreOpeator>
            <div v-else-if="isDustbin" :class="{'bl':hasRouteAuth('crm:orderList:dustbinDelete')}" class="button-text" @click="()=> {$emit('torecoverydialog', scope.row.id)}">还原</div>
          </div>
        </template>
      </u-table-column>
    </u-table>
    <empty-placeholder v-else style="margin-bottom: 24px" />
    <Dialog
      ref="backDialogRef"
      :btn1="'确认'"
      :btn2="'取消'"
      :summary="summary"
      title="订单撤回确认"
      @handelOK="revoke" />
    <Dialog
      ref="publishDialogRef"
      :btn1="'确认提交'"
      :btn2="'暂不提交'"
      summary="请确认是否发布订单"
      title="订单发布确认"
      @handelOK="toPublish" />
    <Dialog
      ref="submitDialogRef"
      :summary="summary"
      :btn1="'确认提交'"
      :btn2="'暂不提交'"
      title="订单提交确认"
      @handelOK="submitCost" />
  </div>
</template>
<script>
import { orderProps } from './settingData';
// img
import { moneyFilter } from '@/filters/number';
// 组件
import platformIcon from '@/components/Common/platformIcon';
import frameContent from '@/components/Common/frameContent';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';

import ResourceInfo from '@/components/ResourceInfo';
import supplierStatus from '@/components/OrderList/dialogComponent/supplierStatus';
import dialogCostlist from '@/components/OrderList/dialogComponent/dialogCostlist';
import detailField from './detailField';
import Examine from '@/components/OrderList/examine';
import Dialog from '@/components/CreateOrder/orderDetail/dialog';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
// 工具方法
import {
  clientStatusFilter, orderTypeStatusFilter, setAccountState,
  setSealBillType, setReviewState, incomeTypeStatusFilter,
  clientSettlementStatus
} from '@/filters/status';
import { getDeptFullName } from '@/filters/dept';
import { hasRouteAuth } from '@/utils/permission';
import ElMessage from '@/utils/message';
import { changeColorAlphaVal } from '@/utils/tools';
import { publishOrder, backOrder, submitCost, linkRequiredCheck } from '@/api/order';
import { standardFormatNoHour, format } from '@/filters/date';
import { mapState } from 'vuex';
// 跨页选中逻辑
import tableSelections from '@/mixins/tableSelections';
import { getSupplierType } from '@/filters/status';

export default {
  components: { Dialog, detailField, platformIcon, ResourceInfo,
    Examine, EmptyPlaceholder, supplierStatus, dialogCostlist, frameContent, MoreOpeator },
  filters: {
    clientStatusFilter,
    orderTypeStatusFilter,
    setAccountState,
    setSealBillType,
    setReviewState,
    incomeTypeStatusFilter,
    standardFormatNoHour,
    moneyFilter, format,
    clientSettlementStatus,
    getDeptFullName,
    getSupplierType,
    orderStatusFilter(status) {
      // orderStatus 0:草稿中 1:待发布 2:待核算 3:待审批 4:待封账 5:封账中 6:已封账 7:已完成
      const arr = ['草稿中', '待发布', '待核算', '待审批', '待封账', '封账中', '已封账', '已完成'];
      return arr[Number(status)];
    }
  },
  mixins: [tableSelections],
  props: {
    listLoading: {
      type: Boolean,
      default: false
    },
    examineLoading: {
      type: Boolean | String,
      default: false
    },
    isDustbin: {
      type: Boolean,
      default: false
    },
    orderListSetting: {
      type: Array,
      default: () => {
        return [];
      }
    },
    activeId: {
      type: Number | String,
      default: ''
    },
    list: {
      type: Object | Array,
      default: () => {
        return {};
      }
    },
    showActionsColumn: {
      type: Boolean,
      default: true
    },
    selectCallback: {
      type: Boolean,
      default: false
    },
    tableHeight: {
      type: String,
      default: '100vh'
    },
    hideSelection: {
      type: Boolean,
      default: false
    },
    isBlank: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      orderProps,
      summary: '',
      orderStatus: null,
      detailInfo: {},
      isSeal: false, // 判断是哪个阶段的撤回，true的话不展示接收人和描述任务输入框
      tableRefName: 'orderTable', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      isUmyTable: true,
      tableKey: 0,
      isLinkRequired: false
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    elementLoadingText() {
      if (!this.examineLoading) return '';
      if (typeof this.examineLoading === 'string') return this.examineLoading;
      return '';
    },
    isClientInfo() {
      return hasRouteAuth('crm:orderList:clientInfo');
    },
    isPublishInfo() {
      return hasRouteAuth('crm:orderList:publishInfo');
    },
    isCostInfo() {
      return hasRouteAuth('crm:orderList:costInfo');
    },
    isOtherInfo() {
      return hasRouteAuth('crm:orderList:otherInfo');
    },
    orderListSettingPure() {
      return this.orderListSetting.filter(item => item.isShow);
    }
  },
  watch: {
    activeId: {
      handler: function() {
        this.$nextTick(() => {
          if (this.clearMixinSelection) this.clearMixinSelection();
        });
      }
    },
    list: {
      handler: function(val, oldval) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val.items);
        });
      },
      deep: true // 对象内部的属性监听，也叫深度监听
    }
  },
  methods: {
    hasRouteAuth,
    changeColorAlphaVal,
    isDeptAuth(item) { // 部门是否符合要求
    /**
     * 协作部门和所属部门，是否存在与与用户的顶级部门或当前部门中
     */
      // 所属部门
      const departmentId = item.attributionMatrixId;
      let cooperationDepartmentIds = []; // 协作部门ID
      if (item.orderInfo.cooperationDepartment && item.orderInfo.cooperationDepartment.length) {
        cooperationDepartmentIds = item.orderInfo.cooperationDepartment.map(i => i.id);
      }

      const currentDeptIds = this.userInfo.currentDeptIds || []; // 当前部门的所有id，比如：用户部门是 研发部->产品组，那么当前部门就是产品组
      const topDeptIds = this.userInfo.topDeptIds || []; // 顶级部门的id列表，比如：用户部门是 研发部->产品组，那么顶级部门就是研发部
      const departmentAry = currentDeptIds.concat(topDeptIds);
      let departmentAuth = false;
      departmentAuth = departmentAry.some(i => {
        return (departmentId === i) || cooperationDepartmentIds.includes(i);
      });

      return departmentAuth;
    },
    isAllAdmin(item) { // 是否有全向权限
      let departmentAuth = false; // 拥有部门全向编辑，当前登录的用户存在该条订单的部门中,或者协作部门中
      if (hasRouteAuth('crm:orderList:adminEdit')) {
        departmentAuth = this.isDeptAuth(item);
      }
      // 全向展示或全向编辑
      return hasRouteAuth('crm:orderList:admin') || departmentAuth;
    },
    isRevokeEditAuth(item) { // 编辑订单权限，只用于撤回按钮判断
      if (hasRouteAuth('crm:orderList:admin')) return true; // 全向展示
      let haveOrderOperator = false; // 当前登录的用户是否在该条订单的执行人中
      if (item.orderInfo.orderOperator && item.orderInfo.orderOperator.length) {
        haveOrderOperator = item.orderInfo.orderOperator.some(i => {
          return i.id === this.userInfo.id;
        });
      }

      let haveOrderMarket = false; // 是否是当前销售
      if (item.clientInfo.marketId) {
        haveOrderMarket = this.userInfo.id === item.clientInfo.marketId;
      }

      let departmentAuth = false; // 拥有部门全向编辑，当前登录的用户存在该条订单的部门中,或者协作部门中
      const isNoOperator = !item.orderInfo.orderOperator || item.orderInfo.orderOperator.length === 0;
      if (hasRouteAuth('crm:orderList:adminEdit') || isNoOperator) {
        departmentAuth = this.isDeptAuth(item);
      }

      //  待审批时：被指定审批人员+审批权限 才有权限
      if (item.orderStatus === 3) {
        return hasRouteAuth('crm:orderList:examine');
      } else {
        return haveOrderOperator || haveOrderMarket || departmentAuth;
      }
    },
    isEditAuth(item) {
      if ((item.orderStatus <= 5 && item.orderStatus >= 4) || item.orderStatus === 2 || item.orderStatus === 1) { return false; }
      if (hasRouteAuth('crm:orderList:admin')) return true; // 全向展示
      let haveOrderOperator = false; // 当前登录的用户是否在该条订单的执行人中
      if (item.orderInfo.orderOperator && item.orderInfo.orderOperator.length) {
        haveOrderOperator = item.orderInfo.orderOperator.some(i => {
          return i.id === this.userInfo.id;
        });
      }

      let haveOrderMarket = false; // 是否是当前销售
      if (item.clientInfo.marketId) {
        haveOrderMarket = this.userInfo.id === item.clientInfo.marketId;
      }

      let departmentAuth = false; // 拥有部门全向编辑，当前登录的用户存在该条订单的部门中,或者协作部门中
      const isNoOperator = !item.orderInfo.orderOperator || item.orderInfo.orderOperator.length === 0;
      if (hasRouteAuth('crm:orderList:adminEdit') || isNoOperator) {
        // 如果执行人为空，则这条订单的所有部门成员都可以编辑
        departmentAuth = this.isDeptAuth(item);
      }
      //  待审批时：被指定审批人员+审批权限 才有权限
      if (item.orderStatus === 3) {
        return hasRouteAuth('crm:orderList:examine');
      } else {
        return haveOrderOperator || haveOrderMarket || departmentAuth;
      }
    },

    isPublishAuth(item) { // 发布权限
      const orderOperator = item.orderInfo ? item.orderInfo.orderOperator : [];
      const userInfo = this.userInfo;
      if (userInfo.userName === '管理员') return true;

      let departmentAuth = false; // 拥有部门全向编辑，当前登录的用户存在该条订单的部门中,或者协作部门中
      const isNoOperator = !item.orderInfo.orderOperator || item.orderInfo.orderOperator.length === 0;
      if (hasRouteAuth('crm:orderList:adminEdit') || isNoOperator) {
        departmentAuth = this.isDeptAuth(item);
      }
      const isOperatorAuth = orderOperator ? orderOperator.some(i => {
        return i.id === userInfo.id;
      }) : false;
      const isMarket = this.userInfo.id === item.clientInfo.marketId;
      return (isOperatorAuth || departmentAuth || isMarket || hasRouteAuth('crm:orderList:admin')) && hasRouteAuth('crm:orderList:publish');
    },
    isExamineAuth() { // 审批权限
      if (this.userInfo.userName === '管理员') return true; // 管理员
      return hasRouteAuth('crm:orderList:examine'); // (isAuditor) &&
    },
    rowClick(row, column, event) {
      if (this.isDustbin) return;
      const notClick = ['操作', '附件', '订单编号', '供应商结算', '成本项列表', '成本项', '账号'];
      if (!notClick.includes(column.label)) {
        this.$router.push({
          name: 'orderDetail',
          params: { orderId: row.id }
        });
      }
    },
    goFlyNoticeDetail(rowData) {
      if (!rowData.queryOrderId) {
        this.$message.warning('无法获取该询单ID');
        return;
      }
      const routeUrl = this.$router.resolve({
        name: 'flyNoticeDetail',
        query: { id: rowData.queryOrderId }
      });
      window.open(routeUrl.href, '_blank');
    },
    btnCheck(scope) {
      this.$router.push({
        name: 'orderDetail',
        params: { orderId: scope.row.id }
      });
    },
    examine(item) {
      const defaultUser = [];
      if (item.clientInfo && item.clientInfo.marketId) {
        defaultUser.push({ id: item.clientInfo.marketId, userName: item.clientInfo.market });
      }
      this.$emit('examine', { ids: item.id, defaultUser });
    },
    btnEdit(scope) {
      const query = {
        sealBillType: scope.row.sealBillType
      };
      if (scope.row.orderStatus === 0) {
        query.draft = 1;
      }
      this.$router.push({
        name: 'editOrder',
        params: { orderId: scope.row.id },
        query: query
      });
    },
    // 变更单
    changeOrder(scope) {
      const lastOrderId = scope.row.lastOrderId || scope.row.id; // 最终单id
      this.$router.push({
        name: 'editOrder',
        params: { orderId: lastOrderId },
        query: { createOrderType: 'change' }
      });
    },
    tableSelectionChange(e) {
      this.$emit('handleSelectionChange', e);
    },
    btnDel(scope) {
      if (scope.row.orderType === 2) {
        this.$confirm('对冲单无法单独删除，请通过删除该对冲单对应的变更单一起删除', '', {
          confirmButtonText: '确定',
          showCancelButton: false,
          center: true,
          type: 'warning',
          customClass: 'del-message',
          iconClass: 'del-icon'
        }).then();
        // ElMessage.error('对冲单无法单独删除，请通过删除该对冲单对应的变更单一起删除');
        return;
      }
      this.$emit('btnDel', scope);
    },
    openSetting() {
      this.$emit('openSetting');
    },
    clearSelection() {
      if (this.$refs.orderTable) this.$refs.orderTable.clearSelection();
    },
    handleTags(tag) {
      if (!Array.isArray(tag) || tag.length === 0) {
        return;
      }
      return tag.slice(0, 3);
    },
    handleStr(tag) {
      if (!Array.isArray(tag) || tag.length === 0) {
        return;
      }
      return tag.map(t => t.name).join();
    },
    getColor(status) {
      // 订单状态： 0: 草稿中 1: 待发布 2: 待核算 3: 待审批 4: 待封账 5: 封账中 6: 已封账 7: 已完成
      let color = '';
      switch (status) {
        case 0:
          color = '#406EFF';
          break;
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
          color = '#FD8546';
          break;
        case 6:
        case 7:
          color = '#31CC9C';
          break;
      }
      return color;
    },
    // 撤回：待发布，待核算，待封账
    revokeDialog(item) {
      this.orderStatus = item.orderStatus;
      let defaultObjectUser = [];
      if (item.orderStatus === 1 && item.clientInfo && item.clientInfo.marketId) {
        defaultObjectUser = [{ id: item.clientInfo.marketId, userName: item.clientInfo.market }];
      } else {
        defaultObjectUser = item.orderInfo.orderOperator;
      }
      let defaultMsg;
      let isSeal;
      // v2.8.8 取消待核算步骤
      // else if (item.orderStatus === 2) {
      //   this.summary = '请确认是否将订单撤回上一步';
      //   defaultMsg = '您有被退回待发布的订单';
      //   isSeal = false;
      // }
      if (item.orderStatus === 1) {
        this.summary = '请确认是否将订单撤回到草稿中';
        defaultMsg = '您的订单信息有误，请及时调整后提交';
        isSeal = false;
      } else if (item.orderStatus === 3) {
        this.summary = '请确认是否将订单撤回上一步';
        defaultMsg = '您有被退回待发布的订单'; // '您有被退回待核算的订单';
        isSeal = false;
      } else if (item.orderStatus === 4) {
        this.summary = '请确认是否将订单撤回上一步';
        isSeal = true;
      }
      this.$refs.backDialogRef.showDialog({
        defaultMsg: defaultMsg, defaultObjectUser, extendParams: { id: item.id, url: `${location.origin}?redirect=/orderPage/orderdetail/${item.id}` }, isSeal: isSeal });
    },
    revoke(data) {
      // v2.8.8 取消待核算(2)步骤
      // else if (this.orderStatus === 2) {
      //   data.status = 1;
      // }
      if (this.orderStatus === 1) {
        data.status = 0;
      } else if (this.orderStatus === 3) {
        data.status = 1;
      } else if (this.orderStatus === 4) {
        data.status = 3;
      }
      data.currentStatus = this.orderStatus;
      backOrder(data).then(res => {
        if (res.code === 200) {
          ElMessage.success('撤回成功');
          this.$emit('fetchData');
          this.opeatorClear(data.id);
        } else {
          ElMessage.success(res.message);
        }
      });
    },
    // 待发布
    toPublishDialog(scope) {
      this.detailInfo = scope.row;
      this.$emit('toSubmit', { isValidate: true, muted: true });
      const defaultUser = [{ id: scope.row.clientInfo.marketId, userName: scope.row.clientInfo.market }];
      this.$refs.publishDialogRef.showDialog({ defaultMsg: '您有新待审批订单需要处理', defaultObjectUser: defaultUser });
      this.handleCheckLinkrequired();
    },
    handleCheckLinkrequired() {
      const { orderFormId, orderPlatformId } = this.detailInfo.orderInfo;
      if (orderFormId && orderPlatformId) {
        const params = {
          orderFormId,
          orderPlatformId
        };
        linkRequiredCheck(params).then(res => {
          if (res.code === 200) {
            this.isLinkRequired = res.data.isRequired;
          }
        }).catch(err => console.error(err));
      }
    },
    toPublish(data) {
      const publishInfo = this.detailInfo.publishInfo || {};
      const orderInfo = this.detailInfo.orderInfo || {};
      if (orderInfo.resourceType !== 2 && this.isLinkRequired) {
        if (!publishInfo.publishUrl) {
          ElMessage.error('请填写发布链接');
          return;
        }
        if (!publishInfo.autoPick && (!publishInfo.publishRemark || !publishInfo.attachment || publishInfo.attachment.length === 0)) {
          ElMessage.error('请填写发布文案和发布截图');
          return;
        }
      }

      data.id = this.detailInfo.id;
      publishOrder(data).then(res => {
        if (res.code === 200) {
          ElMessage.success('发布成功');
          // this.$emit('getInfo');
          this.$emit('fetchData');
          this.opeatorClear(data.id);
        } else {
          ElMessage.success(res.message);
        }
      });
    },
    // 提交核算成本：待核算
    submitCostDialog(scope) {
      this.detailInfo = scope.row;
      const costBreakdown = this.detailInfo.costBreakdown;
      if (costBreakdown.costConfirm === 0) {
        this.summary = '该订单成本未确认，提交后将自动改为已确认，请确认是否提交？';
      } else {
        this.summary = '';
      }
      this.$refs.submitDialogRef.showDialog({ defaultMsg: '您有新待审批订单需要处理', isSubmitCost: true });
    },
    submitCost(data) {
      data.id = this.detailInfo.id.toString();
      data.auditorId = data.receiveUsers;
      submitCost(data).then(res => {
        if (res.code === 200) {
          ElMessage.success('提交成功');
          // this.$emit('getInfo');
          this.$emit('fetchData');
          this.opeatorClear(data.id);
        } else {
          ElMessage.success(res.message);
        }
      });
    },
    sortMethod(a) {
      this.$emit('sortMethod', a);
    },
    opeatorClear(id) {
      if (this.multipleSelectionAll.length > 0) {
        const ids = this.multipleSelectionAll.map(i => Number(i.id));
        if (ids.includes(Number(id)) && this.clearMixinSelection) this.clearMixinSelection();
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.check-tooltip, .eidt-tooltip, .del-tooltip {
  padding: 5px 10px;
}
.flex-center {
  display:flex;
}
.dot {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  margin-right: 5px;
}
.el-table {
  color: #333 !important;
  .order-type {
    padding: 0 5px;
    height:24px;
    border-radius: 16px;
    font-size: 14px;
    @include flexStyle($justify:center, $align: center);
    cursor: pointer;
    img {
      width: 16px;
      height: 16px;
      margin-right: 6px;
    }
  }
  .client-name {
    width: 100%;
  }
  .resource-name {
    width: 120px;
  }
  .theme {
    width: 100px;
  }
}
.tag-wrap{
  display: flex;
  align-items: center;
  .tag{
    color:#406EFF;
    background: #eff4ff;
    display: inline-block;
    max-width: 60px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    height: 20px;
    line-height: 20px;
    font-size: 12px;
    padding: 0px 8px;
    border-radius: 4px;
    margin-right: 4px;
  }
}
</style>

